/*
 * Copyright (c) 2009, DanikX Corporation. All Rights Reserved.
 */

package kz.home.parser;

import kz.home.db.DBUtils;
import kz.home.utils.TimeLog;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.json.me.JSONTokener;

import java.util.Vector;

/**
 * <strong>title</strong>
 * <p> describe
 *
 * @author: Danik <br>
 * Date: 08.07.2009  <br>
 * Time: 16:27:31  <br>
 */
public class JSONParser {

    public void add(Vector vector) {
        for (int i = 0; i < vector.size(); i++) {
            parseString((String) vector.elementAt(i));
        }
    }

    private void parseString(String source) {
        if (source == null || "".equals(source)) return;

        // справочники
        if (source.startsWith("roms[")) parseRooms(source);
        if (source.startsWith("movs[")) parseMovies(source);
        if (source.startsWith("tims[")) parseTimes(source);
        if (source.startsWith("cins[")) parseCinemas(source);

        if (source.startsWith("cits[")) parseCities(source);
        if (source.startsWith("var dates")) parseEvent(source);
    }

    private void parseEvent(String source) {
        int start = source.indexOf("[{");
        int end = source.indexOf("}];");
        try {
            JSONTokener token = new JSONTokener(source.substring(start + 1, end + 1));
            while (token.more()) {
                JSONObject jsonObject = new JSONObject(token);

                DBUtils.saveEvent(getValue(jsonObject, "val"), // 0 дата
                        getValue(jsonObject, "state"), // 1 статус
                        getValue(jsonObject, "dshort"), // 2 статус
                        getValue(jsonObject, "dlong"), // 3 статус
                        getValue(jsonObject, "cit"),  // 4 города
                        getValue(jsonObject, "cin"), //  5 кинотеатры
                        getValue(jsonObject, "mov"), // 6 фильмы
                        getValue(jsonObject, "tim")); // 7 время
                token.skipTo('{');
            }

        } catch (JSONException e) {
            //Resource.getInstance().setError("Error JSON parsing [" + e.getMessage() + "] source[" + source + "]");
            e.printStackTrace();
        }
    }

    private void parseCities(String source) {
        try {
            JSONObject jsonObject = new JSONObject(source.substring(source.indexOf("=") + 1));
            DBUtils.saveCity(
                    getValue(source, '[', ']'),// id города
                    getValue(jsonObject, "val"),   // название города
                            getValue(jsonObject, "state"),  // статус
                            getValue(jsonObject, "cin"),    // кинотеатры
                            getValue(jsonObject, "mov"),    // фильмы
                            getValue(jsonObject, "tim"));   // время
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*private Vector getVector(JSONObject jsonObject, String value) {
        Vector result = new Vector();
        try {
            JSONArray array = jsonObject.getJSONArray(value);
            for (int i = 0; i < array.length(); i++) result.addElement(array.get(i));
        } catch (JSONException e) {
            Resource.getInstance().setError("Error parsing JsonArray [" + e.getMessage() + "] value[" + value + "]");
        }
        return result;
    }*/

    private void parseCinemas(String source) {
        try {
            JSONObject jsonObject = new JSONObject(source.substring(source.indexOf("=") + 1));
            DBUtils.saveCinema(
                    getValue(source, '[', ']'), // id кинотеатра
                    getValue(jsonObject, "val"), // название кинотеатра
                    getValue(jsonObject, "dsc"), // адрес
                    getValue(jsonObject, "state")); // статус
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parseTimes(String source) {
        try {
            JSONObject jsonObject = new JSONObject(source.substring(source.indexOf("=") + 1));
            DBUtils.saveTime(
                    getValue(source, '[', ']'), //id времени
                    getValue(jsonObject, "val"), // значение времени
                    getValue(jsonObject, "state")); // статус
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parseMovies(String source) {
        try {
            JSONObject jsonObject = new JSONObject(source.substring(source.indexOf("=") + 1));
            DBUtils.saveMovies(
                    getValue(source, '[', ']'),// id фильма
                    getValue(jsonObject, "val"), // название фильма
                    getValue(jsonObject, "lid"), // ссылка на фильм
                    getValue(jsonObject, "state")); // статус;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private String getValue(JSONObject jsonObject, String value) {
        try {
            return jsonObject.getString(value);
        } catch (JSONException e) {
            return "";
        }
    }

    private void parseRooms(String source) {
        DBUtils.saveRoom(
                getValue(source, '[', ']'), // id комнаты
                getValue(source, '"') // название компанты
        );
    }

    protected String getValue(String source, char ch_b, char ch_e) {
        if (source == null || "".equals(source)) return "";

        int b = source.indexOf(ch_b);
        int e = source.indexOf(ch_e);
        return source.substring(b + 1, e);
    }

    protected String getValue(String source, char ch) {
        if (source == null || "".equals(source)) return "";

        int b = source.indexOf(ch);
        int e = source.substring(b + 1, source.length()).indexOf(ch);

        return source.substring(b + 1, b + e + 1);
    }

    public void parseAndSaveTimeTable(String source) {
        TimeLog log = new TimeLog();
        int start = source.indexOf("[{");
        int end = source.indexOf("}]");
        try {
            log.start("json");
            JSONTokener token = new JSONTokener(source.substring(start + 1, end + 1));
            int i = 0;
            while (token.more() && i < 10) {
                JSONObject jsonObject = new JSONObject(token);
                DBUtils.saveTimeTable(getValue(jsonObject, "date"), // 0 дата
                        getValue(jsonObject, "cin"), // 1 кинотеатр
                        getValue(jsonObject, "mov"), // 2 фильм
                        getValue(jsonObject, "room"), // 3 зал
                        getValue(jsonObject, "time"),  // 4 время
                        getValue(jsonObject, "price1"), //  5 цена взрослые
                        getValue(jsonObject, "price2"), // 6 цена студенты
                        getValue(jsonObject, "price3")); // 7 цена дети
                token.skipTo('{');
                i++;
            }
            log.stop("json");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        log.print("json");
    }

    /*public static void main(String[] args) {
        Vector vector = new Vector();
        vector.addElement("roms[1]=\"Красный зал\"");
        vector.addElement("roms[2]=\"Зеленый зал\"");
        vector.addElement("roms[3]=\"Синий зал\"");

        vector.addElement("movs[1808]={val: \"100 футов\",lid:15184,state: \"norm\"};");
        vector.addElement("movs[1816]={val: \"Ледниковый период 3. Эра динозавров\",lid:15239,state: \"norm\"};");

        vector.addElement("tims[0]={val: \"10:00\",state: \"norm\"};");
        vector.addElement("tims[7]={val: \"17:00\"};");

        vector.addElement("cins[17]={val: \"Silk Way City\",dsc: \"Толе би 71, уг. Наурызбай батыра. Тел.: 2677-477, 2790-790\",state: \"norm\"};");
        vector.addElement("cins[73]={val: \"Галактика\",dsc: \"Проспект Евразия, 61. Тел.: 8 (7112) 54-09-00, 8 (7112) 51-51-27.\",state: \"dis\"};");

        vector.addElement("cits[1]={val: \"Алматы\",state: \"sec\",cin:[10,11,12,13,14,15,16,17,18,19,21,24,52,62,76],mov:[1750,1759,1765,1783,1789,1797,1798,1806,1807,1808,1811,1813,1814,1815,1816,1817],tim:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]};");
        vector.addElement("cits[2]={val: \"Уральск\",state: \"dis\"};");
        vector.addElement("cits[3]={val: \"Астана\",state: \"dis\",cin:[32],mov:[1811,1813],tim:[2,3,5,6,7,8,9,10,11,12,14]};");

        vector.addElement("var dates = [{val: \"2009-07-01\",state: \"sec\",cit:[1,2,4,5,6,8,18],cin:[10,11,12,13,14,15,16,17,18,19,21,24,32,36,38,39,40,41,52,53,62,76,82],mov:[1746,1750,1759,1762,1763,1765,1783,1789,1790,1791,1792,1797,1798,1806,1807,1808,1811,1813,1814,1815,1816,1817],tim:[1,2,3,4,5,6,7,8,9,10,11,12,13,14],dshort:\"СР, 1 июля\",dlong:\"Среда, 1 июля\"},{val: \"2009-07-02\",state: \"sec\",cit:[1,6],cin:[10,11,12,13,14,15,16,18,21,41,76],mov:[1750,1765,1789,1797,1806,1807,1811,1814,1815,1816],tim:[0,1,2,3,4,5,6,7,8,9,10,11,12,13],dshort:\"ЧТ, 2 июля\",dlong:\"Четверг, 2 июля\"},{val: \"2009-07-03\",state: \"sec\",cit:[1],cin:[21],mov:[1750,1789,1806,1807],tim:[1,3,5,7,9,11],dshort:\"ПТ, 3 июля\",dlong:\"Пятница, 3 июля\"}];");

        JSONParser parser = new JSONParser();
        parser.add(vector);

        Movie movie = (Movie) Resource.getInstance().get(Resource.MOVIE + "." + 1816);
        System.out.println("name=" + movie.getName());
        System.out.println("URL=" + movie.getUrl());
        System.out.println("State=" + movie.getState());
        System.out.println();

        Time time = (Time) Resource.getInstance().get(Resource.TIME + "." + 7);
        System.out.println("time=" + time.getTime());
        System.out.println("State=" + time.getState());
        System.out.println();

        Cinema cinema = (Cinema) Resource.getInstance().get(Resource.CINEMA + "." + 17);
        System.out.println("name=" + cinema.getName());
        System.out.println("Desc=" + cinema.getDesc());
        System.out.println("State=" + cinema.getState());
        System.out.println();

        for (int i = 1; i <= 3; i++) {
            City city = (City) Resource.getInstance().get(Resource.CITY + "." + i);
            System.out.println("name=" + city.getName());
            System.out.println("State=" + city.getState());
            System.out.println("Cinemas =" + city.getCinemas());
            System.out.println("Cinemas lengh=" + city.getCinemas().size());
            System.out.println("Movie =" + city.getMovies());
            System.out.println("Movie lengh=" + city.getMovies().size());
            System.out.println();
        }



        Event event = (Event) Resource.getInstance().get(Resource.EVENT + "." + "2009-07-01");
        System.out.println("date=" + event.getDate());
        System.out.println("State=" + event.getState());
        System.out.println("dshort=" + event.getDshort());
        System.out.println("dlong=" + event.getDlong());

        System.out.println("Cities =" + event.getCities());
        System.out.println("Cities lengh=" + event.getCities().size());

        System.out.println("Cinemas =" + event.getCinemas());
        System.out.println("Cinemas lengh=" + event.getCinemas().size());

        System.out.println("Movie =" + event.getMovies());
        System.out.println("Movie lengh=" + event.getMovies().size());

        System.out.println("Times =" + event.getTimes());
        System.out.println("Times lengh=" + event.getTimes().size());
        System.out.println();

        Event event2 = (Event) Resource.getInstance().get(Resource.EVENT + "." + "2009-07-02");
        System.out.println("date=" + event2.getDate());
        System.out.println("State=" + event2.getState());
        System.out.println("dshort=" + event2.getDshort());
        System.out.println("dlong=" + event2.getDlong());

        System.out.println("Cities =" + event2.getCities());
        System.out.println("Cities lengh=" + event2.getCities().size());

        System.out.println("Cinemas =" + event2.getCinemas());
        System.out.println("Cinemas lengh=" + event2.getCinemas().size());

        System.out.println("Movie =" + event2.getMovies());
        System.out.println("Movie lengh=" + event2.getMovies().size());

        System.out.println("Times =" + event2.getTimes());
        System.out.println("Times lengh=" + event2.getTimes().size());
        System.out.println();

    }*/
}